package cn.yunyichina.provider.drug.service.impl;

import cn.yunyichina.provider.drug.dao.DeliveryDao;
import cn.yunyichina.provider.drug.dao.MatchedOutDao;
import cn.yunyichina.provider.drug.entity.Delivery;
import cn.yunyichina.provider.drug.entity.MatchedOut;
import cn.yunyichina.provider.drug.utils.DateUtils;
import cn.yunyichina.provider.drug.vo.Order;
import cn.yunyichina.provider.drug.vo.OrderList;
import cn.yunyichina.provider.framework.common.PKGenerator;
import cn.yunyichina.provider.framework.dubbo.service.*;
import cn.yunyichina.provider.framework.page.PageInfo;
import cn.yunyichina.provider.iface.entity.base.OrderExtVo;
import cn.yunyichina.provider.iface.entity.cache.SessionInfo;
import cn.yunyichina.provider.iface.entity.common.ResCommon;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.common.ResponseObject;
import cn.yunyichina.provider.iface.entity.drug.DeliveryVo;
import cn.yunyichina.provider.iface.entity.merchant.BusinessCallRequestDto;
import cn.yunyichina.provider.iface.entity.merchant.NotifyMessageRequestDto;
import cn.yunyichina.provider.iface.entity.merchant.NotifyScene;
import cn.yunyichina.provider.iface.entity.message.AppMessageVo;
import cn.yunyichina.provider.iface.entity.message.TemplateCode;
import cn.yunyichina.utils.convert.JsonUtils;
import cn.yunyichina.utils.log.Log;
import cn.yunyichina.utils.log.constant.LogParamType;
import cn.yunyichina.utils.log.constant.LogScene;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2017/7/21.
 */
@Service
public class OrderServiceImpl {

    private Logger logger = LoggerFactory.getLogger(OrderServiceImpl.class);

    @Autowired
    private DeliveryDao deliveryDao;

    @Autowired
    private MatchedOutDao matchedOutDao;

    @Resource
    private Properties yaml;

    /**
     * 订单记录查询接口(对外接口)
     * yyt.drug.order.item.out.list
     * @param data
     * @return
     */
    public Response listOrderItemOut(String data) {
        logger.info("【订单记录查询接口(对外接口)】开始, 请求=" + data);
        Response response = new Response();

        try {
            Map<String,String> vo = JsonUtils.parseObject(data,Map.class);
            String companyCode = vo.get("company_code");
            String drugStoreCode = vo.get("drug_store_code");
            String hospitalCode = vo.get("hospital_code");
            String deliveryMethod = vo.get("delivery_method");
            String checkStatus = vo.get("check_status");
            String beginTime = vo.get("begin_time");
            String endTime = vo.get("end_time");
            String pageNum = vo.get("page_num");
            String pageSize = vo.get("page_size");

            if(StringUtils.isBlank(companyCode)){
                response.setResultCodeAndMessage("7", "company_code不能为空");
                logger.info("【订单记录查询接口(对外接口)】结束, 返回结果=" + JsonUtils.toJsonString(response));
                return response;
            }

            if(StringUtils.isBlank(pageNum)){
                response.setResultCodeAndMessage("7", "page_num不能为空");
                logger.info("【订单记录查询接口(对外接口)】结束, 返回结果=" + JsonUtils.toJsonString(response));
                return response;
            }
            if(StringUtils.isBlank(pageSize)){
                response.setResultCodeAndMessage("7", "page_size不能为空");
                logger.info("【订单记录查询接口(对外接口)】结束, 返回结果=" + JsonUtils.toJsonString(response));
                return response;
            }

            String pattern = "yyyy-MM-dd HH:mm:ss";
            if(StringUtils.isNotBlank(beginTime)){
                if(!DateUtils.isValidDate(beginTime,pattern)){
                    response.setResultCodeAndMessage("9", "接口mehod参数出错，begin_time时间格式非法");
                    logger.info("【订单记录查询接口(对外接口)】结束, 返回结果=" + JsonUtils.toJsonString(response));
                    return response;
                }
            }
            if(StringUtils.isNotBlank(endTime)){
                if(!DateUtils.isValidDate(endTime,pattern)){
                    response.setResultCodeAndMessage("9", "接口mehod参数出错，end_time时间格式非法");
                    logger.info("【订单记录查询接口(对外接口)】结束, 返回结果=" + JsonUtils.toJsonString(response));
                    return response;
                }
            }
            if(StringUtils.isNotBlank(checkStatus)){
                Integer status = Integer.valueOf(checkStatus);
                if(!(status==0?true:status==1?true:status==2?true:status==3?true:status==4?true:status==5?true:false)){
                    response.setResultCodeAndMessage("9", "check_status值非法");
                    logger.info("【订单记录查询接口(对外接口)】结束, 返回结果=" + JsonUtils.toJsonString(response));
                    return response;
                }
            }

            PageInfo pageInfo = new PageInfo();
            pageInfo.setPageNum(Integer.valueOf(pageNum));
            pageInfo.setPageSize(Integer.valueOf(pageSize));

            List<Map<String, Object>> list = deliveryDao.listOrderItemOut(companyCode, drugStoreCode, hospitalCode, deliveryMethod, checkStatus, null, beginTime, endTime, pageInfo);
            logger.info("【订单记录查询接口(对外接口)】查询到" + list.size() +"条数据");

            if(list.size() == 0){
                response.setResultCodeAndMessage("14", "查无数据");
                logger.info("【订单记录查询接口(对外接口)】结束, 返回结果=" + JsonUtils.toJsonString(response));
                return response;
            }

            Map<String, Object> map = new HashMap<String, Object>();
            map.put("list",list);

            if(pageInfo.getPageNum() != null && pageInfo.getPageSize() != null){
                long count = deliveryDao.listOrderItemOutCount(companyCode, drugStoreCode, hospitalCode, deliveryMethod, checkStatus, null, beginTime, endTime);
                pageInfo.setTotal(count);
                pageInfo.setPages((pageInfo.getTotal().intValue() + pageInfo.getPageSize() - 1) / pageInfo.getPageSize());
                map.put("page_info",pageInfo);
            }

            response.setResult(JsonUtils.toJsonString(map));
            response.setResultCodeAndMessage("0", "成功");
        } catch (Exception e) {
            e.printStackTrace();
            response.setResultCodeAndMessage("1", "系统级别异常:" + e.getMessage());
        }

        logger.info("【订单记录查询接口(对外接口)】结束, 返回结果=" + JsonUtils.toJsonString(response));
        return response;
    }


    /**
     * 订单明细查询接口(对外接口)
     * yyt.drug.order.out.detail
     * @param data
     * @return
     */
    public Response detailOrderOut(String data) {
        logger.info("【订单明细查询接口(对外接口)】开始, 请求=" + data);
        Response response = new Response();

        try {
            Map<String,String> vo = JsonUtils.parseObject(data,Map.class);
            String orderNo = vo.get("order_no");

            if(StringUtils.isBlank(orderNo)){
                response.setResultCodeAndMessage("7", "order_no不能为空");
                logger.info("【订单明细查询接口(对外接口)】结束, 返回结果=" + JsonUtils.toJsonString(response));
                return response;
            }

            List<Map<String, Object>> list = deliveryDao.listOrderItemOut(null, null, null, null, null, orderNo, null, null, null);
            logger.info("【订单明细查询接口(对外接口)】查询到list=" + list.size() +"条数据");
            List<Map<String, Object>> detail = deliveryDao.detailOrderOut(null, orderNo);
            logger.info("【订单明细查询接口(对外接口)】查询到detail=" + detail.size() +"条数据");

            if(list.size() == 0){
                response.setResultCodeAndMessage("14", "查无数据");
                logger.info("【订单明细查询接口(对外接口)】结束, 返回结果=" + JsonUtils.toJsonString(response));
                return response;
            }

            Map<String, Object> result = list.get(0);
            result.put("detail",detail);

            response.setResult(JsonUtils.toJsonString(result));
            response.setResultCodeAndMessage("0", "成功");
        } catch (Exception e) {
            e.printStackTrace();
            response.setResultCodeAndMessage("1", "系统级别异常:" + e.getMessage());
        }

        logger.info("【订单明细查询接口(对外接口)】结束, 返回结果=" + JsonUtils.toJsonString(response));
        return response;
    }

    /**
     * 订单处理接口(对外接口)
     * yyt.drug.order.update
     * @param data
     * @return
     */
    public Response updateOrder(String data) {
        logger.info("【订单处理接口(对外接口)】开始, 请求=" + data);
        Response response = new Response();

        try {
            Map<String,String> vo = JsonUtils.parseObject(data,Map.class);
            String orderNo = vo.get("order_no");
            String dealFlag = vo.get("deal_flag");
            String opinions = vo.get("opinions");

            if(StringUtils.isBlank(orderNo)){
                response.setResultCodeAndMessage("7", "order_no不能为空");
                return response;
            }
            if(StringUtils.isBlank(dealFlag)){
                response.setResultCodeAndMessage("7", "deal_flag不能为空");
                return response;
            }

            if(!"1".equals(dealFlag) && !"2".equals(dealFlag) && !"3".equals(dealFlag) && !"5".equals(dealFlag)){
                response.setResultCodeAndMessage("9", "接口mehod参数出错，deal_flag非法");
                return response;
            }

            Map<String, String> ordQueryMap = new HashMap<String, String>();
            ordQueryMap.put("order_no",orderNo);
            Response ordResponse = BaseService.callUnderlineFromInternal("",
                    "yyt.base.order.by.orderno.get", JsonUtils.toJsonString(ordQueryMap));
            if(!"0".equals(ordResponse.getResultCode())){
                logger.error("【订单处理接口(对外接口)】查询订单失败 " + orderNo);
                response.setResultCodeAndMessage("2", "callFromInternal处理异常");
                return response;
            }
            OrderExtVo order = JsonUtils.parseObject(ordResponse.getResult(), OrderExtVo.class);
            if(order == null){
                logger.error("【订单处理接口(对外接口)】查询订单为空 订单号=" + orderNo + ",ordResponse="+ JSON.toJSONString(ordResponse));
                response.setResultCodeAndMessage("9", "接口mehod参数出错，order_no非法");
                return response;
            }

            if("1".equals(dealFlag) || "2".equals(dealFlag)){
                if(!("2".equals(order.getOrderStatus().toString()) && "3".equals(order.getPayStatus().toString()) && "10".equals(order.getOrderType().toString()))){
                    logger.error("【订单处理接口(对外接口)】接/拒单失败，当前订单不支持该操作, 订单类型=" + order.getOrderType() + ",订单状态=" + order.getOrderStatus() + ",支付状态=" + order.getPayStatus());
                    response.setResultCodeAndMessage("9", "接口mehod参数出错，当前订单不支持该操作");
                    return response;
                }
            }

            if("3".equals(dealFlag)){
                if(!(("2".equals(order.getOrderStatus().toString()) || "3".equals(order.getOrderStatus().toString()) || "5".equals(order.getOrderStatus().toString())) && "5".equals(order.getPayStatus().toString()) && "10".equals(order.getOrderType().toString()))){
                    logger.error("【订单处理接口(对外接口)】同意退费失败，本订单类型错误或用户未申请退费, 订单类型=" + order.getOrderType() + ",订单状态=" + order.getOrderStatus() + ",支付状态=" + order.getPayStatus());
                    response.setResultCodeAndMessage("9", "接口mehod参数出错，当前订单不支持该操作");
                    return response;
                }
            }

            if("5".equals(dealFlag)){
                if(!(("2".equals(order.getOrderStatus().toString()) || "3".equals(order.getOrderStatus().toString())) && "5".equals(order.getPayStatus().toString()) && "10".equals(order.getOrderType().toString()))){
                    logger.error("【订单处理接口(对外接口)】拒绝退费失败，本订单类型错误或用户未申请退费, 订单类型=" + order.getOrderType() + ",订单状态=" + order.getOrderStatus() + ",支付状态=" + order.getPayStatus());
                    response.setResultCodeAndMessage("9", "接口mehod参数出错，当前订单不支持该操作");
                    return response;
                }
            }

            Delivery delivery = deliveryDao.selectByOrderNo(orderNo);
            if(delivery == null){
                logger.error("【订单处理接口(对外接口)】查询配送单为空 订单号=" + orderNo);
                response.setResultCodeAndMessage("9", "接口mehod参数出错，order_no非法");
                return response;
            }

            if("1".equals(dealFlag)){
                order.setOrderStatus(OrderExtVo.ORDER_STATUS_SUCCESS);
                delivery.setOrderStatus(DeliveryVo.ORDER_STATUS_SUCCESS);
                sendMsg2user(order,2);
            }else if("2".equals(dealFlag)){
                try {
                    //第三方原渠道退费
                    Map<String, Object> jsonMap = new HashMap<String, Object>();
                    jsonMap.put("hospital_code", order.getOrgCode());
                    jsonMap.put("order_no", order.getOrderNo());
                    if (1 == order.getIsInsurance()) {//没有医保的订单
                        Map<String, Object> extraParams = JsonUtils.parseObject(order.getExtraParams(), Map.class);
                        jsonMap.put("his_order_no", extraParams.get("cancel_bill_no"));
                        jsonMap.put("his_serial_no", extraParams.get("cancel_serial_no"));
                        jsonMap.put("refund_amount", order.getTotalAmount());
                    } else {
                        jsonMap.put("his_order_no", order.getHisOrderNo());
                        jsonMap.put("refund_amount", order.getPayAmount());
                    }
                    jsonMap.put("refund_time", cn.yunyichina.utils.commons.DateUtils.dateToString(new Date()));
                    jsonMap.put("refund_reason", "拒单");
                    jsonMap.put("refund_flag", 1);
                    jsonMap.put("push_type", 0);
                    Response refundResponse = PayService.callUnderlineFromInternal("", "yyt.pay.refund.channel.origin", JsonUtils.toJsonString(jsonMap));
                    logger.info("【订单处理接口(对外接口)】：退费返回" + JsonUtils.toJsonString(refundResponse) + ",订单号：" + order.getOrderNo());
                    if ("0".equals(refundResponse.getResultCode())) {
                        order.setPayStatusRefunded();
                        order.setOrderStatus(OrderExtVo.ORDER_PAY_STATUS_REFUNDED);
                        delivery.setOrderStatus(OrderExtVo.ORDER_PAY_STATUS_REFUNDED);
                        response.setResultCodeAndMessage("0", "成功");
                    } else {
                        order.setPayStatusWaitRefund();//第三方退费失败，状态改成待退费
                        order.setOrderStatus(OrderExtVo.ORDER_PAY_STATUS_REFUNDED);
                        delivery.setOrderStatus(OrderExtVo.ORDER_PAY_STATUS_WAIT_REFUND);
                        response.setResultCodeAndMessage("2", "callFromInternal处理异常");
                    }
                    delivery.setOperationResponse("订单拒单退费结果：" + JsonUtils.toJsonString(refundResponse));
                }catch (Exception e){
                    logger.info("【订单处理接口(对外接口)】调用原渠道退费发送异常" + orderNo + ",异常：" + e.getMessage());
                    order.setPayStatusWaitRefund();//第三方退费失败，状态改成待退费
                    delivery.setOrderStatus(OrderExtVo.ORDER_PAY_STATUS_WAIT_REFUND);
                    delivery.setOperationResponse("订单拒单退费异常：" + e.getMessage());
                    response.setResultCodeAndMessage("2", "callFromInternal处理异常");
                }

                //发送拒单模板消息
                sendMsg2user(order,3);
            }else if("3".equals(dealFlag)) {
                try {
                    //第三方原渠道退费
                    Map<String, Object> jsonMap = new HashMap<String, Object>();
                    jsonMap.put("hospital_code", order.getOrgCode());
                    jsonMap.put("order_no", order.getOrderNo());
                    if (1 == order.getIsInsurance()) {//没有医保的订单
                        Map<String, Object> extraParams = JsonUtils.parseObject(order.getExtraParams(), Map.class);
                        jsonMap.put("his_order_no", extraParams.get("cancel_bill_no"));
                        jsonMap.put("his_serial_no", extraParams.get("cancel_serial_no"));
                        jsonMap.put("refund_amount", order.getTotalAmount());
                    } else {
                        jsonMap.put("his_order_no", order.getHisOrderNo());
                        jsonMap.put("refund_amount", order.getPayAmount());
                    }
                    jsonMap.put("refund_time", cn.yunyichina.utils.commons.DateUtils.dateToString(new Date()));
                    jsonMap.put("refund_reason", "用户取消");
                    jsonMap.put("refund_flag", 1);
                    jsonMap.put("push_type", 0);
                    Response refundResponse = PayService.callUnderlineFromInternal("", "yyt.pay.refund.channel.origin", JsonUtils.toJsonString(jsonMap));
                    logger.info("【订单处理接口(对外接口)】：退费返回" + JsonUtils.toJsonString(refundResponse) + ",订单号：" + order.getOrderNo());
                    if ("0".equals(refundResponse.getResultCode())) {
                        order.setPayStatusRefunded();
                        order.setOrderStatus(OrderExtVo.ORDER_PAY_STATUS_REFUNDED);
                        delivery.setOrderStatus(OrderExtVo.ORDER_PAY_STATUS_REFUNDED);
                        response.setResultCodeAndMessage("0", "成功");
                    } else {
                        order.setPayStatusWaitRefund();//第三方退费失败，状态改成待退费
                        order.setOrderStatus(OrderExtVo.ORDER_PAY_STATUS_REFUNDED);
                        delivery.setOrderStatus(OrderExtVo.ORDER_PAY_STATUS_WAIT_REFUND);
                        response.setResultCodeAndMessage("2", "callFromInternal处理异常");
                    }
                    delivery.setOperationResponse("订单审核退费结果：" + JsonUtils.toJsonString(refundResponse));
                } catch (Exception e) {
                    logger.info("【订单处理接口(对外接口)】调用原渠道退费发送异常" + orderNo + ",异常：" + e.getMessage());
                    order.setPayStatusWaitRefund();//第三方退费失败，状态改成待退费
                    delivery.setOrderStatus(OrderExtVo.ORDER_PAY_STATUS_WAIT_REFUND);
                    delivery.setOperationResponse("审批退费异常：" + e.getMessage());
                    response.setResultCodeAndMessage("2", "callFromInternal处理异常");
                }
            }else if("5".equals(dealFlag)){
                order.setPayStatusPayed();
                response.setResultCodeAndMessage("0", "成功");
            }

            delivery.setOperationType(Short.parseShort(dealFlag));
            delivery.setOperators("第三方调用");
            delivery.setOpinions(opinions);
            delivery.setUpdateTime(cn.yunyichina.utils.commons.DateUtils.dateToString(new Date()));

            deliveryDao.update(delivery);
            BaseService.callUnderlineFromInternal("","yyt.base.order.update", JsonUtils.toJsonString(order));

            response.setResultCodeAndMessage("0", "成功");
        } catch (Exception e) {
            e.printStackTrace();
            response.setResultCodeAndMessage("1", "系统级别异常:" + e.getMessage());
        }

        logger.info("【订单处理接口(对外接口)】结束, 返回结果=" + JsonUtils.toJsonString(response));
        return response;
    }


    /**
     *
     * @param order
     * @param type 1:支付成功消息 2：接单 3：拒单消息
     */
    public void sendMsg2user(OrderExtVo order,int type){
        // 消息推送
        try {
            String url=yaml.getProperty("order.clinic.url")+"order_no="+order.getOrderNo()+"&app_code="+order.getPlatformOrgAppCode()+"&open_id="+order.getOpenId()+"&app_id="+order.getPayAppId();
            short platformType = 2;
            if ("1".equals(String.valueOf(Integer.valueOf(order.getPayMode())/10%10))) {
                platformType = 1;
            }else if("2".equals(String.valueOf(Integer.valueOf(order.getPayMode())/10%10))){
                platformType = 2;
            }

            AppMessageVo appMessageVo = new AppMessageVo();
            appMessageVo.setOpenId(order.getOpenId());
            appMessageVo.setPlatformOrgAppCode(order.getPlatformOrgAppCode());
            appMessageVo.setDevOrgCode(order.getPlatformCode());
            appMessageVo.setLibraryTemplateType((short) 3);
            appMessageVo.setPlatformType(platformType);
            appMessageVo.setUrl(url);

            Map<String,String> map = new HashedMap();
            switch (type){
                case 1://支付成功消息
                    appMessageVo.setPlatformTemplateCode(TemplateCode.PBM_PAY_SUCCESS.getCode());
                    map.put("orderNo",order.getOrderNo());
                    map.put("details","门特处方");
                    map.put("amount",order.getPayAmount()/100d + "元");
                    break;
                case 2://接单
                    appMessageVo.setPlatformTemplateCode(TemplateCode.PBM_GET_ORDER.getCode());
                    map.put("name",order.getOrgName());//药店名称
                    map.put("orderNo",order.getOrderNo());
                    break;
                case 3://拒单
                    appMessageVo.setPlatformTemplateCode(TemplateCode.PBM_REFUSE_ORDER.getCode());
                    map.put("orderNo",order.getOrderNo());
                    map.put("orderType","门特处方外购");
                    map.put("amount",order.getPayAmount()/100d + "元");
                    map.put("time",order.getPayTime().length() > 20?order.getPayTime().substring(0,19):order.getPayTime());
                    map.put("cause","药店没有接单。");
                    break;

            }
            appMessageVo.setMsgContentMap(map);
            Log.i(LogScene.PBM, "OrderServiceImpl.sendMsg2user", LogParamType.REQUEST, order.getOrderNo(),
                    "PBM外购单order系统消息推送接口,入参request=" + JsonUtils.toJsonString(appMessageVo));
            ResponseObject messageResponse = MessageService.getMessageClient().sendAppMessage(appMessageVo);
            Log.i(LogScene.PBM, "OrderServiceImpl.sendMsg2user", LogParamType.RESPONSE, order.getOrderNo(),
                    "PBM外购单order系统消息推送接口,调用message模块, 返回response=" + JsonUtils.toJsonString(messageResponse));

        } catch (Exception e) {
            logger.error("处方外购, 支付成功后消息推送失败:", e);
        }
    }


    /**
     * 订单推送接口(推送到第三方系统)
     * yyt.drug.order.item.out.push
     * @param data
     * @return
     */
    public Response pushOrderItemOut(String data) {
        logger.info("【订单推送接口(推送到第三方系统)】开始, 请求=" + data);
        Response response = new Response();

        Map<String,String> vo = JsonUtils.parseObject(data,Map.class);
        String orderNo = vo.get("order_no");
        String checkStatus = vo.get("check_status");

        try {
            if(StringUtils.isBlank(orderNo)){
                response.setResultCodeAndMessage("7", "order_no不能为空");
                logger.info("【订单推送接口(推送到第三方系统)】结束, 返回结果=" + JsonUtils.toJsonString(response));
                return response;
            }

            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put("order_no", orderNo);
            dataMap.put("order_type", OrderExtVo.ORDER_TYPE_CLINIC_BUY_OUT);
            logger.info("【订单推送接口(推送到第三方系统)】 yyt.base.order.by.orderno.get request=" + JSON.toJSONString(dataMap));
            Response ordResponse = BaseService.callUnderlineFromInternal("yyt.base.order.by.orderno.get",
                    JsonUtils.toJsonString(dataMap));
            logger.info("【订单推送接口(推送到第三方系统)】 yyt.base.order.by.orderno.get response=" + JSON.toJSONString(ordResponse));
            if (!"0".equals(ordResponse.getResultCode())) {
                response.setResultCodeAndMessage(ordResponse.getResultCode(), ordResponse.getResultMessage());
                return response;
            }
            Order order = JSON.parseObject(ordResponse.getResult(), Order.class);

            if(order == null){
                logger.error("【订单推送接口(推送到第三方系统)】" + orderNo + "订单不存在或非法订单");
                response.setResultCodeAndMessage("23002", orderNo + "订单不存在或非法订单");
                return response;
            }else{
                if("0".equals(checkStatus)){
                    if(!("2".equals(order.getOrderStatus().toString()) && "3".equals(order.getPayStatus().toString()) && ("10".equals(order.getOrderType().toString()) || "3".equals(order.getOrderType().toString())))){
                        logger.error("【订单推送接口(推送到第三方系统)】推送失败，当前订单不支持该操作, 订单类型=" + order.getOrderType() + ",订单状态=" + order.getOrderStatus() + ",支付状态=" + order.getPayStatus());
                        response.setResultCodeAndMessage("23002", "推送失败，当前订单不支持该操作");
                        return response;
                    }
                }else if("1".equals(checkStatus)){
                    if(!(("2".equals(order.getOrderStatus().toString()) || "3".equals(order.getOrderStatus().toString())) && "5".equals(order.getPayStatus().toString()) && "10".equals(order.getOrderType().toString()))){
                        logger.error("【订单推送接口(推送到第三方系统)】推送失败，本订单类型错误, 订单类型=" + order.getOrderType() + ",订单状态=" + order.getOrderStatus() + ",支付状态=" + order.getPayStatus());
                        response.setResultCodeAndMessage("23009", "推送失败，当前订单不支持该操作");
                        return response;
                    }
                }else{
                    response.setResultCodeAndMessage("7", "check_status类型不正确");
                    logger.info("【订单推送接口(推送到第三方系统)】结束, 返回结果=" + JsonUtils.toJsonString(response));
                    return response;
                }

                NotifyMessageRequestDto requestDto=new NotifyMessageRequestDto();
                Map<String,String> map = new HashMap<>();
                map.put("check_status", checkStatus);
                map.put("order", JSON.toJSONString(order));

                requestDto.setMessageContent(JSON.toJSONString(map));
                requestDto.setNotifyScene(NotifyScene.ORDER_PAYED_NOTIFY);
                requestDto.setOrderNo(order.getOrderNo());
                requestDto.setOrgCode(order.getOrgCode());
                requestDto.setOrgName(order.getOrgName());
                logger.info("【订单推送接口(推送到第三方系统)】 notifyMessage request=" + JSON.toJSONString(requestDto));
                ResCommon<Void> notifyRespons = MerchantService.getMerchantService().notifyMessage(requestDto);
                logger.info("【订单推送接口(推送到第三方系统)】 notifyMessage respons=" + JSON.toJSONString(notifyRespons));
                if (!"0".equals(notifyRespons.getResultCode())) {
                    response.setResultCodeAndMessage(notifyRespons.getResultCode(), notifyRespons.getResultMessage());
                    return response;
                }
            }

            response.setResultCodeAndMessage("0", "成功");
        } catch (Exception e) {
            e.printStackTrace();
            response.setResultCodeAndMessage("23999", "系统异常:" + e.getMessage());
        }

        logger.info("【订单推送接口(推送到第三方系统)】结束, 返回结果=" + JsonUtils.toJsonString(response));
        return response;
    }


    /**
     * 药店目录查询接口(对外接口)
     * yyt.drug.order.hospital.drug.list
     * @param data
     * @return
     */
    public Response listOrderHospitalDrug(String data) {
        logger.info("【药店目录查询接口(对外接口)】开始, 请求=" + data);
        Response response = new Response();

        try {
            Map<String,String> vo = JsonUtils.parseObject(data,Map.class);
            String hospitalCode = vo.get("hospital_code");
            String beginTime = vo.get("begin_time");
            String endTime = vo.get("end_time");
            String pageNum = vo.get("page_num");
            String pageSize = vo.get("page_size");

            if(StringUtils.isBlank(hospitalCode)){
                response.setResultCodeAndMessage("7", "hospital_code不能为空");
                logger.info("【药店目录查询接口(对外接口)】结束, 返回结果=" + JsonUtils.toJsonString(response));
                return response;
            }

            String pattern = "yyyy-MM-dd HH:mm:ss";
            if(StringUtils.isNotBlank(beginTime)){
                if(!DateUtils.isValidDate(beginTime,pattern)){
                    response.setResultCodeAndMessage("9", "接口mehod参数出错，begin_time时间格式非法");
                    logger.info("【药店目录查询接口(对外接口)】结束, 返回结果=" + JsonUtils.toJsonString(response));
                    return response;
                }
            }
            if(StringUtils.isNotBlank(endTime)){
                if(!DateUtils.isValidDate(endTime,pattern)){
                    response.setResultCodeAndMessage("9", "接口mehod参数出错，end_time时间格式非法");
                    logger.info("【药店目录查询接口(对外接口)】结束, 返回结果=" + JsonUtils.toJsonString(response));
                    return response;
                }
            }

            PageInfo pageInfo = null;
            if(StringUtils.isNotBlank(pageNum) || StringUtils.isNotBlank(pageSize)){
                if(StringUtils.isBlank(pageNum)){
                    response.setResultCodeAndMessage("7", "page_num不能为空");
                    logger.info("【药店目录查询接口(对外接口)】结束, 返回结果=" + JsonUtils.toJsonString(response));
                    return response;
                }
                if(StringUtils.isBlank(pageSize)){
                    response.setResultCodeAndMessage("7", "page_size不能为空");
                    logger.info("【药店目录查询接口(对外接口)】结束, 返回结果=" + JsonUtils.toJsonString(response));
                    return response;
                }

                pageInfo = new PageInfo();
                pageInfo.setPageNum(Integer.valueOf(pageNum));
                pageInfo.setPageSize(Integer.valueOf(pageSize));
            }


            List<Map<String, Object>> list = deliveryDao.getHospitalList(hospitalCode, beginTime, endTime, pageInfo);
            logger.info("【药店目录查询接口(对外接口)】查询到" + list.size() +"条数据");

            if(list.size() == 0){
                response.setResultCodeAndMessage("14", "查无数据");
                logger.info("【药店目录查询接口(对外接口)】结束, 返回结果=" + JsonUtils.toJsonString(response));
                return response;
            }

            Map<String, Object> map = new HashMap<String, Object>();
            map.put("list",list);

            if(pageInfo != null){
                long count = deliveryDao.getHospitalListCount(hospitalCode, beginTime, endTime);
                pageInfo.setTotal(count);
                pageInfo.setPages((pageInfo.getTotal().intValue() + pageInfo.getPageSize() - 1) / pageInfo.getPageSize());
                map.put("page_info",pageInfo);
            }

            response.setResult(JsonUtils.toJsonString(map));
            response.setResultCodeAndMessage("0", "成功");
        } catch (Exception e) {
            e.printStackTrace();
            response.setResultCodeAndMessage("1", "系统级别异常:" + e.getMessage());
        }

        logger.info("【药店目录查询接口(对外接口)】结束, 返回结果=" + JsonUtils.toJsonString(response));
        return response;
    }


    /**
     * 订单药品匹配接口(调用第三方系统)
     * yyt.drug.order.item.out.mathed
     * @param data
     * @return
     */
    public Response mathedOrderItemOut(String data) {
        logger.info("【订单药品匹配接口(调用第三方系统)】开始, 请求=" + data);
        Response response = new Response();

        try {
            Map<String,String> vo = JsonUtils.parseObject(data,Map.class);
            String orgCode = vo.get("org_code");
            String orgName = vo.get("org_name");
            String orderNo = vo.get("order_no");
            String longitude = vo.get("longitude");
            String latitude = vo.get("latitude");
            String deliveryMethod = vo.get("delivery_method");

            if(StringUtils.isBlank(orgCode)){
                response.setResultCodeAndMessage("7", "org_code不能为空");
                logger.info("【订单药品匹配接口(调用第三方系统)】结束, 返回结果=" + JsonUtils.toJsonString(response));
                return response;
            }
            if(StringUtils.isBlank(orgName)){
                response.setResultCodeAndMessage("7", "org_name不能为空");
                logger.info("【订单药品匹配接口(调用第三方系统)】结束, 返回结果=" + JsonUtils.toJsonString(response));
                return response;
            }
            if(StringUtils.isBlank(orderNo)){
                response.setResultCodeAndMessage("7", "order_no不能为空");
                logger.info("【订单药品匹配接口(调用第三方系统)】结束, 返回结果=" + JsonUtils.toJsonString(response));
                return response;
            }
            if(StringUtils.isBlank(longitude)){
                response.setResultCodeAndMessage("7", "longitude不能为空");
                logger.info("【订单药品匹配接口(调用第三方系统)】结束, 返回结果=" + JsonUtils.toJsonString(response));
                return response;
            }
            if(StringUtils.isBlank(latitude)){
                response.setResultCodeAndMessage("7", "latitude不能为空");
                logger.info("【订单药品匹配接口(调用第三方系统)】结束, 返回结果=" + JsonUtils.toJsonString(response));
                return response;
            }
            if(StringUtils.isBlank(deliveryMethod)){
                response.setResultCodeAndMessage("7", "delivery_method不能为空");
                logger.info("【订单药品匹配接口(调用第三方系统)】结束, 返回结果=" + JsonUtils.toJsonString(response));
                return response;
            }else{
                Integer method = Integer.valueOf(deliveryMethod);
                if(!(method==1?true:method==2?true:false)){
                    response.setResultCodeAndMessage("9", "接口mehod参数出错，delivery_method格式非法");
                    logger.info("【订单药品匹配接口(调用第三方系统)】结束, 返回结果=" + JsonUtils.toJsonString(response));
                    return response;
                }
            }

            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put("order_no", orderNo);
            dataMap.put("order_type", OrderExtVo.ORDER_TYPE_CLINIC_BUY_OUT);
            logger.info("【订单药品匹配接口(调用第三方系统)】 yyt.base.order.by.orderno.get request=" + JSON.toJSONString(dataMap));
            Response ordResponse = BaseService.callUnderlineFromInternal("yyt.base.order.by.orderno.get",
                    JsonUtils.toJsonString(dataMap));
            logger.info("【订单药品匹配接口(调用第三方系统)】 yyt.base.order.by.orderno.get response=" + JSON.toJSONString(ordResponse));
            if (!"0".equals(ordResponse.getResultCode())) {
                response.setResultCodeAndMessage(ordResponse.getResultCode(), ordResponse.getResultMessage());
                return response;
            }
            Order order = JSON.parseObject(ordResponse.getResult(), Order.class);

            if(order == null){
                logger.error("【订单药品匹配接口(调用第三方系统)】" + orderNo + "订单不存在或非法订单");
                response.setResultCodeAndMessage("23002", orderNo + "订单不存在或非法订单");
                return response;
            }else{
                List<OrderList> listItem = order.getListItem();
                if(listItem == null || listItem.size() == 0){
                    logger.error("【订单药品匹配接口(调用第三方系统)】匹配失败，订单" + orderNo + "处方数据为空");
                    response.setResultCodeAndMessage("23002", "匹配失败，订单" + orderNo + "处方数据为空");
                    return response;
                }

                if(!("1".equals(order.getOrderStatus().toString()) && ("1".equals(order.getPayStatus().toString()) || "2".equals(order.getPayStatus().toString())) && ("10".equals(order.getOrderType().toString()) || "3".equals(order.getOrderType().toString())))){
                    logger.error("【订单药品匹配接口(调用第三方系统)】匹配失败，当前订单不支持该操作, 订单类型=" + order.getOrderType() + ",订单状态=" + order.getOrderStatus() + ",支付状态=" + order.getPayStatus());
                    response.setResultCodeAndMessage("23002", "当前订单不支持该操作");
                    return response;
                }

                Map<String,String> mapBusiness = new HashMap<>();
                mapBusiness.put("longitude", longitude);
                mapBusiness.put("latitude", latitude);
                mapBusiness.put("delivery_method", deliveryMethod);
                mapBusiness.put("order", JSON.toJSONString(order));

                BusinessCallRequestDto requestDto=new BusinessCallRequestDto();
                requestDto.setBusinessContent(JSON.toJSONString(mapBusiness));
                requestDto.setNotifyScene(NotifyScene.ORDER_MATHED_LIST);
                requestDto.setOrderNo(order.getOrderNo());
                requestDto.setOrgCode(orgCode);
                requestDto.setOrgName(orgName);
                logger.info("【订单药品匹配接口(调用第三方系统)】 businessCall request=" + JSON.toJSONString(requestDto));
                Response businessCallRespons = MerchantService.getMerchantService().businessCall(requestDto);
                logger.info("【订单药品匹配接口(调用第三方系统)】 businessCall respons=" + JSON.toJSONString(businessCallRespons));
                if (!"0".equals(businessCallRespons.getResultCode())) {
                    response.setResultCodeAndMessage("23009", "匹配失败:" + businessCallRespons.getResultMessage().replace("\"",""));
                    return response;
                }else{
                    response.setResultCodeAndMessageAndResult("0", "成功", businessCallRespons.getResult());
                }

                MatchedOut matchedOutQuery = new MatchedOut();
                matchedOutQuery.setOrderNo(orderNo);
                matchedOutQuery.setCompanyCode(orgCode);
                List<MatchedOut> matchedOutListQuery = matchedOutDao.select(matchedOutQuery);
                if(matchedOutListQuery != null && matchedOutListQuery.size() > 0){
                    List<String> idList = new ArrayList<>();
                    for (MatchedOut matchedOut : matchedOutListQuery) {
                        idList.add(matchedOut.getId());
                    }
                    if(idList != null && idList.size() > 0){
                        matchedOutDao.deleteByIds(idList);
                    }
                }

                List<MatchedOut> matchedOutList = JSON.parseArray(businessCallRespons.getResult(), MatchedOut.class);
                for (MatchedOut matchedOut : matchedOutList) {
                    matchedOut.setId(PKGenerator.generateId());
                    matchedOut.setOrderNo(orderNo);
                    matchedOut.setMatchedNo(orderNo);
                    matchedOut.setCompanyCode(orgCode);
                    matchedOut.setCompanyName(orgName);
                    matchedOut.setCreatedTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                }
                matchedOutDao.batchInsert(matchedOutList);
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setResultCodeAndMessage("23999", "系统异常:" + e.getMessage());
        }

        logger.info("【订单药品匹配接口(调用第三方系统)】结束, 返回结果=" + JsonUtils.toJsonString(response));
        return response;
    }
}
